package itsm.isperp.framework.web.servlet;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.UploadInfo;
import itsm.isperp.framework.service.UploadFileService;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2015-3-13
 * @since 1.0
 * 
 */
public class DownloadFileServlet extends HttpServlet implements
		InitializingBean {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected UploadFileService<UploadInfo> uploadFileService;

	/**
	 * 初始化
	 */
	@Override
	public void init() throws ServletException {

		if (this.uploadFileService == null) {
			this.uploadFileService = ContextHolder
					.getSpringBean("appUploadFileService");// 此处可设置为可配置

		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		String id = req.getParameter("id");

		if (StringUtils.isEmpty(id)) {
			return;
		}
		UploadInfo uf = uploadFileService.findOne(id);

		String path = uf.getPath();
		String filePath = ContextHolder.getApplicationPath() + path;
		File f = new File(filePath);
		if (!f.exists()) {

			resp.setContentType("text/html;charset=UTF-8");

			resp.getWriter().write("文件不存在！");
			return;
		}
		long fileLength = f.length();

		resp.setContentType(uf.getContentType());
		resp.setHeader("Content-disposition", "attachment; filename="
				+ java.net.URLEncoder.encode(uf.getName(), "utf-8"));

		resp.setHeader("Content-Length", String.valueOf(fileLength));

		bis = new BufferedInputStream(new FileInputStream(filePath));
		bos = new BufferedOutputStream(resp.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
	}

	@Override
	public void afterPropertiesSet() throws Exception {

	}
}
